package com.grace.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Producer;
import com.grace.common.Result;
import com.grace.pojo.User;
import com.grace.service.LoginService;


/**
 * 
*    
* 类名称：LoginController   
* 类描述：   login控制器
* 创建人：zhourunmin   
* 创建时间：2017年6月27日 上午10:30:17  
* 备注：   
* @version    
*
 */
@Controller
@RequestMapping("/login")
public class LoginController {
	@Autowired
	private Producer producer;
	@Autowired
	private LoginService loginService;

	
	@RequestMapping(value="/login",method = RequestMethod.POST)
	@ResponseBody
	public Result login (HttpServletRequest request, String username,String password,String captcha){
		HttpSession session = request.getSession();
		String text = null;
		Result result = null;
		User user = null;
		try {
			text = session.getAttribute("captchaText").toString();
			if (!StringUtils.equals(text, captcha)) {
				result = new Result(101, "验证码错误!");
				return result;
			}else
			{
				user = loginService.login(username,password);
				if (user != null) {
					user.setPassword("");
					session.setAttribute("user", user);
				}
				else {
					return new Result(102,"用户名密码错误！");
				}
			}
			
			result=new Result(200,"登录成功",user);
			 
		} catch (Exception e) {
			result=new Result(103,"账号异常!");
			System.out.println("#######登录异常是："+e+"######");
		}
		
		return result;
	}
	
	@RequestMapping("captcha.jpg")
	public void creatCaptcha(HttpServletRequest request ,HttpServletResponse response) throws Exception{
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");
		String text = producer.createText();
		BufferedImage image = producer.createImage(text);
		HttpSession session = request.getSession();
		session.setAttribute("captchaText", text);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
	}
	@RequestMapping(value="logout",method=RequestMethod.POST)
	@ResponseBody
	public Result logout(HttpServletRequest request){
		try {
			HttpSession session = request.getSession();
			session.removeAttribute("user");
		} catch (Exception e) {
			System.out.println("#######注销异常是："+e+"######");
			return new Result(105, "注销失败");
		}
		return new Result(200,"注销成功");
	}
	
}
